<template>
  <el-container>
    <el-header>
      <el-button type="success" style="float: left; margin-left: 20px"
                 @click="openRoleForm(undefined)"
        >添加角色
      </el-button>
    </el-header>
    <el-main>
      <el-table :data="roles" stripe height="300" style="width: 100%" ref="table"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" :selectable="row => row.id !== 1"/>
        <el-table-column prop="name" label="角色名" width="180"/>
        <el-table-column prop="des" label="描述"/>
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button
                type="text"
                size="small"
                @click.prevent="openRoleForm(roles[scope.$index])">
              编辑
            </el-button>
            <el-button
                type="text"
                size="small"
                v-show="roles[scope.$index].id !== 1"
                @click.prevent="deleteRole(roles[scope.$index])">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="danger" style="float: left; margin: 20px" @click="bathDelete">批量删除</el-button>
    </el-main>
  </el-container>
  <el-dialog v-model="roleDialog">
    <el-form class="register_form" label-width="80px" ref="registerForm" :model="roleForm">
      <h3>{{ currentRole? '编辑': '添加'}}角色</h3>
      <el-form-item label="角色名">
        <el-input
            v-model="roleForm.name"
            type="text"
            autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="描述">
        <el-input
            v-model="roleForm.des"
            type="text"
            autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="分配权限">
        <el-checkbox-group v-model="hasPermissions" >
          <el-checkbox v-for="permission in permissions" :label="permission.des" :key="permission.id"/>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label-width="0xp">
        <el-button type="primary" @click="saveRole">{{ currentRole? '编辑': '添加'}}</el-button>
        <el-button @click="roleDialog = false">返回</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <el-dialog v-model="deleteDialogVisible" title="警告" width="30%" center>
    <span>
      是否确定删除角色: {{ pendingDelete.map(p => p.des).toString() }}？
    </span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDelete"
        >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ElMessage } from "element-plus";
import {ref} from "vue";

export default {
  name: "RoleDetails",
  data() {
    return {
      roles:[],
      multipleSelection: [],
      roleDialog: ref(false),
      roleForm: {},
      currentRole: undefined,
      hasPermissions: [],
      permissions: [],
      pendingDelete: [],
      deleteDialogVisible: ref(false)
    }
  },
  mounted() {
    this.loadRoles()
  },
  methods: {
    loadRoles() {
      let _this = this
      this.$axios.get("role/list")
      .then(success => {
        if (success.data.code === 200) {
          _this.roles = success.data.data
        } else {
          ElMessage({
            message: success.data.message,
            type: 'error'
          })
        }
      })
      .catch(fail => {
        console.log(fail);
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    saveRole(){
      let _this = this
      let has = this.hasPermissions.map(value => this.permissions.find(permission => permission.des === value))
      this.$axios.post('role/save', {role: this.roleForm, hasPermissions: has})
          .then(success => {
            if (success.data.code === 200) {
              ElMessage({
                message: '保存成功',
                type: 'success'
              })
              _this.loadRoles()
              _this.roleDialog = ref(false)
            } else {
              ElMessage({
                message: success.data.message,
                type: 'error'
              })
            }
          })
          .catch(fail => {
            console.log(fail);
          })
    },
    openRoleForm(role) {
      this.currentRole = role
      this.roleForm = role || {}
      let _this = this
      if (this.permissions.length === 0) {
        this.$axios.get('permission/list')
            .then(success => {
              if (success.data.code === 200) {
                _this.permissions = success.data.data
              } else {
                ElMessage({
                  message: success.data.message,
                  type: 'error'
                })
              }
            })
            .catch(fail => {
              console.log(fail);
            })
      }
      if (this.currentRole) {
        this.$axios.post('permission/has', this.currentRole)
            .then(success => {
              if (success.data.code === 200) {
                _this.hasPermissions = success.data.data.map(value => value.des)
                this.roleDialog = ref(true)
              } else {
                ElMessage({
                  message: success.data.message,
                  type: 'error'
                })
              }
            })
            .catch(fail => {
              console.log(fail);
            })
      } else {
        this.hasPermissions = []
        this.roleDialog = ref(true)
      }
    },
    deleteRole(role){
      this.pendingDelete = [role]
      this.deleteDialogVisible = ref(true)
    },
    bathDelete(){
      this.pendingDelete = this.multipleSelection
      this.deleteDialogVisible = ref(true)
    },
    confirmDelete() {
      this.deleteDialogVisible = ref(false)
      let _this = this
      this.$axios.post("role/delete", this.pendingDelete)
          .then(success => {
            if (success.data.code === 200) {
              ElMessage({
                message: '删除成功',
                type: 'success'
              })
              _this.loadRoles()
            } else {
              ElMessage({
                message: success.data.message,
                type: 'error'
              })
            }
          }).catch(fail => {
        console.log(fail)
      })

    }
  }
}
</script>

<style scoped>

</style>